<template>
  <a-drawer
      title="收支流水列表"
      :maskClosable="true"
      :visible="visible"
      :width="$store.getters.isMobile ? 350 : 1000"
      :body-style="{ paddingBottom: '80px' }"
      @close="closeModal"
  >
    <a-alert type="info" v-if="!processApprove" style="margin-bottom: 10px;">
      <template #message>
        匹配流水暂未开启审批，点击”
        <span v-if="Approveis_admin" class="link" @click.stop="goSetting">配置</span>
        <span v-else class="link" style="cursor: not-allowed;">配置</span>
        “可快速设置。
      </template>
    </a-alert>
    <a-row type="flex" align="middle">
      <a-col :flex="1">
        <a-input-search
            v-model:value="keywords"
            placeholder="搜索单位名称、房号"
            enter-button
            @search="onKeywordsSearch"
            allow-clear
        />
      </a-col>
      <a-col>
        <div style="display: flex">
          <div class="switch-wrap">
            <a-switch
                v-model:checked="isExpandOwner"
                checked-children="显示"
                un-checked-children="隐藏"
                @change="onOwnerSwitchChange"
            />
            <span
                style="font-size: 12px; padding: 0 8px">{{
                `已${isExpandOwner ? '显示' : '隐藏'}其他${$L("租客")}收支流水`
              }}</span>
          </div>
        </div>
      </a-col>
    </a-row>

    <a-table
        :dataSource="dataList"
        :columns="columns"
        :loading="loading"
        :row-selection="rowSelection"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        class="mt-10"
        :scroll="{ x: 'max-content' }"
    >
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'match_status'">
          <a-badge v-if="text == 2" status="error"/>
          <a-badge v-if="text == 3" status="warning"/>
          <span>{{ record.match_status_txt }}</span>
        </template>
        <template v-if="column.key === 'price'">
          <span>{{ text }}元</span>
        </template>
      </template>

      <template
          #customFilterDropdown="{
          setSelectedKeys,
          selectedKeys,
          confirm,
          clearFilters,
          column,
        }"
      >
        <template v-if="column.key === 'income_date'">
          <div style="padding: 12px">
            <a-range-picker
                v-model:value="incomeDateRange"
                @change="
                (dates, dateStrs) => handleIncomeDateChange(dateStrs, confirm)
              "
            />
          </div>
        </template>
      </template>
    </a-table>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="closeModal">取消</a-button>
        <a-button
            type="primary"
            @click.prevent="matchToAccount"
            :disabled="selectedRowKeys.length == 0"
        >匹配
        </a-button
        >
      </a-space>
    </div>
    <!-- 匹配弹窗 -->
    <a-modal
        v-model:visible="showMatchModal"
        title="流水匹配"
        centered
        @ok="onSubmit"
        :confirmLoading="matchLoading"
        :width="600"
    >
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="onSubmit">
          {{ processApprove ? '确定&发起审批' : '确定' }}
        </a-button>
      </template>
      <a-form layout="vertical">
        <a-row :gutter="12">
          <a-col :span="12">
            <a-form-item label="匹配金额（元）" v-bind="validateInfos.amount">
              <a-input-number
                  class="w-100p"
                  placeholder="请输入匹配金额"
                  v-model:value="matchParams.amount"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="匹配时间" v-bind="validateInfos.match_date">
              <a-date-picker
                  class="w-100p"
                  v-model:value="matchParams.match_date"
                  :value-format="dateFormatStr"
                  :disabled-date="disabledDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-descriptions layout="vertical" bordered>
              <a-descriptions-item :label="typeTxt + '需' + billTypeTxt">
                {{ matchParams.actual_retreat }}元
              </a-descriptions-item>
              <a-descriptions-item label="流水未匹配">
                {{ matchParams.nomatch_prices }}元
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>
        <a-row v-if="processApprove" :gutter="24" style="margin-top: 10px;">
          <a-col :span="24">
            <a-form-item label="审批备注">
              <a-textarea
                  v-model:value="matchParams.approval_remark"
                  :auto-size="{ minRows: 3, maxRows: 6 }"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </a-drawer>
</template>

<script>
import {defineComponent, watch, reactive, toRefs, computed, ref} from "vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import moment from "moment";
import {Form, message} from "ant-design-vue";
import utils from "@/common/utils/utils";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";

export default defineComponent({
  name: "BillDetailMatchTurnover",
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "bill", // bill匹配账单 latefee 匹配滞纳金
    },
    cost_type: {
      type: String,
      default: "",
    },
    village_id: {
      type: Number,
      default: 0,
    },
    // 租客信息 {id, name}
    ownerInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props, context) {
    const today = moment().format(dateFormatStr);
    const disabledDate = (current) => {
      return current && current < moment().subtract(1, "days").endOf("day");
    };

    const billTypeTxt = computed(
        () => store.getters.billMatchAccountDetail.bill_type_txt
    );

    const typeTxt = computed(() => (props.type === "bill" ? "账单" : "滞纳金"));

    const matchToAccount = () => {
      /*console.log(
        "matchToAccount",
        props.type,
        store.getters.billMatchAccountDetail.amount,
        store.getters.billMatchAccountDetail.latefeeAmount
      );*/
      matchParams.actual_retreat =
          props.type == "bill"
              ? Number(store.getters.billMatchAccountDetail.amount)
              : Number(store.getters.billMatchAccountDetail.latefeeAmount);
      matchParams.nomatch_prices = 0;
      for (let item of state.selectedRows) {
        matchParams.nomatch_prices += Number(item.nomatch_price);
      }
      matchParams.amount =
          matchParams.actual_retreat > matchParams.nomatch_prices
              ? matchParams.nomatch_prices
              : matchParams.actual_retreat;
      state.showMatchModal = true;
    };
    const closeModal = () => {
      context.emit("cancel");
    };

    const onSubmit = () => {
      let msgContent = "";
      if (matchParams.amount < 0) {
        msgContent = "匹配金额不能小于0";
      }
      if (
          matchParams.nomatch_prices > matchParams.actual_retreat &&
          matchParams.amount > matchParams.actual_retreat
      ) {
        msgContent = `匹配金额不能大于${typeTxt.value}需${billTypeTxt.value}金额`;
      }
      if (
          matchParams.actual_retreat > matchParams.nomatch_prices &&
          matchParams.amount > matchParams.nomatch_prices
      ) {
        msgContent = "匹配金额不能大于勾选的流水未匹配总金额";
      }
      if (msgContent) {
        message.error(msgContent);
        return;
      }
      state.matchLoading = true;
      let params = {
        bill_id: store.getters.billMatchAccountDetail.bill_id,
        bill_type: store.getters.billMatchAccountDetail.bill_type,
        stream_ids: state.selectedRowKeys.join(","),
        approval: state.processApprove,
        needMsg: true,
        ...matchParams,
      };
      let requestUrl = "/bill/streamMatchBatch";
      if (props.type == "latefee") {
        requestUrl = "/bill/streamMatchLate";
        params.need_latefee = matchParams.actual_retreat;
        delete params.actual_retreat;
      }
      request.post("/org", requestUrl, params).then((res) => {
        message.success(res.msg || "匹配成功！");
        state.showMatchModal = false;
        context.emit("success");
      }).finally(() => {
        state.matchLoading = false;
      });
    };

    const state = reactive({
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      loading: false,
      selectedRowKeys: [],
      selectedRows: [],
      optionData: {},
      showMatchModal: false,
      isExpandOwner: false,
      // 是否有审批
      processApprove: true,
      Approveis_admin: false,
      Approve_id: 0,
      matchLoading: false,
    });

    const searchParams = reactive({
      keywords: "",
      order: "",
      sort: "",
      stream_source: "",
      match_status: "",
      income_date_start: "",
      income_date_end: "",
    });

    const matchParams = reactive({
      amount: "",
      approval_remark: "",
      match_date: today,
      actual_retreat: 0,
      nomatch_prices: 0,
    });
    const matchRule = ref({
      amount: [{required: true, message: "必填"}],
      match_date: [{required: true, message: "必填"}],
    });
    const {resetFields, validate, validateInfos} = useForm(
        matchParams,
        matchRule
    );

    const incomeDateRange = ref([]);
    const handleIncomeDateChange = (dateArr, confirm) => {
      confirm();
      searchParams.income_date_start = dateArr[0];
      searchParams.income_date_end = dateArr[1];
      state.page = 1;
      getTableData();
    };

    const onKeywordsSearch = () => {
      if (state.page == 1) {
        getTableData();
      } else {
        state.page = 1;
      }
    };

    watch(
        () => searchParams.keywords,
        (val) => {
          if (!val) {
            onKeywordsSearch();
          }
        }
    );

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));

    const rowSelection = computed(() => ({
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectChange,
    }));

    const onSelectChange = (selectedRowKeys, selectedRows) => {
      state.selectedRowKeys = selectedRowKeys;
      state.selectedRows = selectedRows;
    };

    const columns = computed(() => {
      const {streamSource, match_status} = state.optionData;
      return [
        {
          title: "入账日期",
          key: "income_date",
          dataIndex: "income_date",
          width: 150,
          fixed: "left",
          sorter: true,
          customFilterDropdown: true,
        },
        {
          title: "借贷标",
          key: "loan_type_txt",
          dataIndex: "loan_type_txt",
          width: 120,
          fixed: store.getters.isMobile ? undefined : "left",
        },
        {
          title: "对方单位名称",
          key: "company_name",
          dataIndex: "company_name",
          width: 180,
          fixed: store.getters.isMobile ? undefined : "left",
        },
        {
          title: "自建/导入",
          key: "stream_source_txt",
          dataIndex: "stream_source_txt",
          width: 120,
          filters:
              streamSource && streamSource.length
                  ? streamSource.map((item) => ({
                    text: item.name,
                    value: item.key,
                  }))
                  : null,
        },
        {
          title: "发生额",
          key: "price",
          dataIndex: "amount",
          width: 120,
          sorter: true,
        },
        {
          title: "已匹配金额",
          key: "price",
          dataIndex: "match_price",
          width: 150,
        },
        {
          title: "未匹配金额",
          key: "price",
          dataIndex: "nomatch_price",
          width: 150,
          sorter: true,
        },
        {
          title: "摘要",
          key: "abstract",
          dataIndex: "abstract",
          width: 180,
        },
        {
          title: "匹配状态",
          key: "match_status",
          dataIndex: "match_status",
          width: 120,
          filters:
              match_status && match_status.length
                  ? match_status.map((item) => ({
                    text: item.name,
                    value: item.key,
                  }))
                  : null,
        },
      ];
    });
    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      // console.log("filters", filters);
      // console.log("sorter", sorter);
      // 排序
      if (sorter.order) {
        searchParams.order = sorter.field;
        searchParams.sort = sorter.order === "ascend" ? "asc" : "desc";
      } else {
        searchParams.order = "";
        searchParams.sort = "";
      }
      // 自建、导入类型
      searchParams.stream_source =
          filters.stream_source_txt && filters.stream_source_txt.length
              ? filters.stream_source_txt.join(",")
              : "";

      // 匹配状态
      searchParams.match_status =
          filters.match_status && filters.match_status.length
              ? filters.match_status.join(",")
              : "";

      getTableData();
    };

    const getTableData = () => {
      state.loading = true;
      const params = {
        cost_type: props.cost_type,
        village_id: props.village_id,
        page: state.page,
        limit: state.limit,
        bill_type: store.getters.billMatchAccountDetail?.loan_type == 'PAY' ? 2 : store.getters.billMatchAccountDetail.bill_type,
        bill_id: store.getters.billMatchAccountDetail.bill_id,
      };
      for (let key in searchParams) {
        if (searchParams[key]) {
          params[key] = searchParams[key];
        }
      }
      if (props.ownerInfo.id && !state.isExpandOwner) {
        params.owner_id = props.ownerInfo.id;
      }
      params.match_date = moment(params.match_date).format(dateFormatStr);
      request
          .get("/org", "/bill/getStreamList", params)
          .then((res) => {
            state.total = res.total;
            state.dataList = res.list;
          })
          .finally(() => {
            state.loading = false;
          });
    };

    const init = () => {
      state.isExpandOwner = store.getters.matchTurnoverShowOtherOwner;
      store.dispatch("SetBMTInit").then((res) => {
        state.optionData = res;
      });
      getTableData();
    };

    const reset = () => {
      resetFields();
      onSelectChange([], []);
      state.matchLoading = false;
    };

    const onOwnerSwitchChange = (checked) => {
      store.dispatch("setMatchTurnoverShowOtherOwner", checked).then(() => {
        state.page = 1;
        getTableData();
      });
    };

    const getSetting = () => {
      // 获取配置
      request.get("/org", "/approval/publish/process", {
        alias: 'bill_stream_match'
      }).then((res) => {
        state.processApprove = res.info.process    //判断是否开启
        state.Approveis_admin = res.info.is_admin    //判断是否有权限
        state.Approve_id = res.info.id
      });
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };


    const handleCancel = () => {
      state.showMatchModal = false
    };

    watch(
        () => store.getters.matchTurnoverShowOtherOwner,
        (val) => {
          state.isExpandOwner = val;
        }
    );

    watch(
        () => props.visible,
        (visible) => {
          if (visible) {
            init();
          } else {
            reset();
          }
          getSetting();
        }
    );
    return {
      ...toRefs(state),
      ...toRefs(searchParams),
      matchParams,
      validateInfos,
      pagination,
      columns,
      rowSelection,
      incomeDateRange,
      dateFormatStr,
      billTypeTxt,
      typeTxt,
      closeModal,
      matchToAccount,
      onKeywordsSearch,
      handleTableChange,
      handleIncomeDateChange,
      onSubmit,
      disabledDate,
      onOwnerSwitchChange,
      getSetting,
      goSetting,
      handleCancel,
    };
  },
});
</script>
<style lang="less" scoped>
.switch-wrap {
  margin-left: 16px;
  background-color: #f2f2f2;
  border-radius: 20px;
  padding: 5px 10px;
  display: flex;
  align-items: center;
}
</style>
